from re import DEBUG
from flask import jsonify
from qwen_agent.agents import Assistant
from qwen_agent.log import logger

logger.setLevel(DEBUG)

def init_agent_server():
  llm_cfg = {
    'model': 'qwen2.5-VL-7b',
    'model_server': 'http://192.168.88.150:7890/v1',
    'api-key': 'EMPTY',

    'generate_cfg': {
      'top_p': 0.7,
    }
  }
  system = ('你是一个家庭小能手，能够帮助主人处理各种琐事，还能回答主人的问题')
  
  # define mcp
  tools = [
    {
      "mcpServers": {
        "time": {
          "command": "python",
          "args": ["-m", "mcp_server_time"]
        },
      }
    }
  ]

  bot = Assistant(llm=llm_cfg, 
                  name='AiHubBot',
                  description='A home assistant',
                  system_message=system,
                  function_list=tools
                  )
  return bot

# bot is global
bot = init_agent_server()
messages = []

# define the agent
def agent_tui(bot, msg):

  # chat, clear message
  # on edge device, the longer context, the slower performance
  if msg in ['clear', 'reset', 'well done', 'good job', 'thank you for your help']:
    print('msg = ', msg)
    messages.clear()
    print('messages = ', messages)
    return [{'role': 'assistant', 'content': 'thank you.', 'name': 'AiHubBot'}]

  messages.append({'role': 'user', 'content': msg})
  print(messages)
  response = []
  for response in bot.run(messages):
    pass
  messages.extend(response)
  print('ai bot response:', response)
  return response
